#!/bin/bash

WORK_DIR=`dirname $0`

# Check arguments
if (( $# < 4 )); then
	echo "Uso: $0  <host> <database> <database_user> <database_password>"
	exit 1
fi

DB_HOST=$1
DB_NAME=$2
DB_USER=$3
DB_PASSWORD=$4


if ! [ -f  ~/.pgpass ]; then
	echo "$DB_HOST:5432:*:$DB_USER:$DB_PASSWORD" >> ~/.pgpass
	chmod 0600 ~/.pgpass
fi

echo "** Initializing database... "
psql -U $DB_USER -h $DB_HOST -c "drop database if exists $DB_NAME;" template1
createdb -e -E UNICODE -O $DB_USER -e -U $DB_USER -h $DB_HOST $DB_NAME
createlang -e -U $DB_USER -h $DB_HOST plpgsql $DB_NAME

echo "** Creating database..."
psql -U $DB_USER -h $DB_HOST -f $WORK_DIR/sql/create.sql $DB_NAME


echo "** Loading initial data..."
psql -U $DB_USER -h $DB_HOST -f $WORK_DIR/sql/data/min-data.sql $DB_NAME
echo "** Loading councils..."
psql -U $DB_USER -h $DB_HOST -f $WORK_DIR/sql/data/councils.sql $DB_NAME

echo "** Creating analysis views..."
psql -U $DB_USER -h $DB_HOST -f $WORK_DIR/sql/analysis/analysis.sql $DB_NAME

echo "** Creating indexes..."
psql -U $DB_USER -h $DB_HOST -f $WORK_DIR/sql/analysis/indexes.sql $DB_NAME

echo "** Creating archive..."
psql -U $DB_USER -h $DB_HOST -f $WORK_DIR/sql/archive/archive.sql $DB_NAME

echo "** Creating process files functions..."
psql -U $DB_USER -h $DB_HOST -f $WORK_DIR/sql/load/load.sql $DB_NAME